<?php
/**
 * @author elson <elsonwu@126.com>
 */
class excel
{
	function excel() 
	{
		global $admin;
		
		if(empty($_SESSION["managerid"])) 
			$admin->login();
	}
	
	/**
	 * 输出excel下载
	 */
	function index()
	{
		global $segment;
		$filename = isset($segment[3]) ? $segment[3] : 'excel';
		$filename .= ('_'.date('Y-m-d').'.xls');
		$saveFilename = 'caches/'.$filename;
		
		if(isset($_POST['ajax']) && isset($_POST['data']))
		{
			$data = trim($_POST['data']);
			
			//删除上一次的遗留缓存
			if(file_exists($saveFilename))
				unlink($saveFilename);

			//清除多余的注释
			$data = preg_replace("/<!--.*-->/isU", '', $data);	
			
			if(isset($data{10}))
				file_put_contents($saveFilename, $data);
			else
				throw new Exception('缺少内容，无法正常生成excel文件');
		}
		else
		{
			//查找不到show这个参数，或show的值是get，都进行excel输出
			if('get' === url::get('show', 'get'))
			{
				if(file_exists($saveFilename))
				{
					header("Pragma: public");  
					header("Expires: 0");
					Header('Content-type: application/octet-stream;charset=utf-8');
					header("Content-Type: application/vnd.ms-excel");  
					header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
					header("Content-Type: application/force-download");  
					header("Content-Type: application/download");
					Header('Accept-Ranges:bytes');
					Header("Accept-Length: ".filesize($saveFilename)); 
					header("Content-Disposition: attachment;filename=".$filename);  
					header("Content-Transfer-Encoding: binary");
					echo file_get_contents($saveFilename);
					
					unlink($saveFilename);
				}
				else
					throw new Exception($filename.' 无法正常生成');
			}
		}
		
		//退出脚本，不加载模板
		exit;
	}
	
	//编码转换/已废弃
	public function toGBK($data)
	{
		if(function_exists('mb_detect_encoding') && function_exists('iconv'))
		{
			$charsetNow = mb_detect_encoding($data);
			$charsetTo = "gb2312";
			
			if($charsetNow != $charsetTo)
				$data = iconv($charsetNow, $charsetTo, $data);
		}
		
		return $data;
	}
}